
use log::{info, trace};
use serde::Deserialize;

use crate::{app_config, AppError, cliargs::TranslateRule, subtitles::SubTitles};
/*
const res = await fetch("http://40.125.174.167:5000/translate", {
    method: "POST",
    body: JSON.stringify({
        q: "",
        source: "auto",
        target: "sq",
        format: "text",
        api_key: ""
    }),
    headers: { "Content-Type": "application/json" }
});
console.log(await res.json());
*/
pub async fn translate(subtitles:&mut SubTitles,trans_rule:&Option<TranslateRule>)->Result<(),AppError>{
    let trans_rule=trans_rule.unwrap_or(TranslateRule::TranslateDown);
    for subtitle in subtitles{
      info!("{}",subtitle.content);
       let translated= transalte_single(subtitle.content.as_str()).await?;
       trace!("{}",translated);
       subtitle.add_translate(translated,&trans_rule);
    }
    Ok(())
}

async fn transalte_single(text: &str) -> Result<String, AppError> {
    let app_config = app_config::AppConfig::get();

    let url = format!("{}/translate", app_config.libretranslate_url());
    let mut body = std::collections::HashMap::new();
    body.insert("q", text);
    body.insert("target", app_config.libretranslate_target_lang());
    body.insert("source", "auto");
    body.insert("format", "text");
    body.insert("api_key", app_config.libretranslate_api_key());

    let client = reqwest::Client::new();
    let resp = client.post(url).json(&body).send().await?;
    let resp= resp.json::<TranslateResponse>().await.unwrap();
    trace!("{:?}", resp);
    Ok(resp.translatedText)
}

#[derive(Deserialize,Debug)]
#[allow(non_snake_case)]
struct TranslateResponse {
    translatedText: String,
}